<template>
  <div class="private-message-container">
    <!-- 左侧：搜索框和对话列表 -->
    <div class="private-left-panel">
      <div class="search-container">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索联系人（姓名/电话/角色）"
            class="search-input"
            @keyup.enter.native="handleSearch"
        >
          <template #prefix>
            <el-icon @click="handleSearch" class="search-icon"><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 所有对话 -->
      <div v-if="hasConversations" class="conversation-section">
        <div class="section-title">所有对话 ({{ messageItemStore.allConversations?.length || 0 }})</div>

        <div
            v-for="conversation in messageItemStore.allConversations || []"
            :key="conversation.id"
            :class="conversation.isReadCon ? 'conversation-card' : 'conversation-card unread'"
            @click.stop="openConversation(conversation)"
        >

          <el-avatar
              :size="48"
              :src="conversation && conversation.starterId===currentUser.id ? conversation.participant?.avatar : conversation.starter?.avatar"
              class="conversation-avatar"
          />
          <div class="conversation-content">
            <div class="conversation-name">{{conversation && conversation.starterId===currentUser.id ? conversation.participant?.name : conversation.starter?.name}}</div>
<!--            <div class="conversation-preview">{{ conversation && conversation.latestMessage.content || '暂无消息' }}</div>-->
            <div class="conversation-preview">{{ conversation && conversation.latestMessage && conversation.latestMessage.content? conversation.latestMessage?.content : '暂无消息' }}</div>
          </div>
<!--          <div class="conversation-time">{{ conversation && formatDateTime(conversation.latestMessage.messageTime).display }}</div>-->
          <div class="conversation-time">{{ conversation && conversation.latestMessage && conversation.latestMessage.messageTime? formatDateTime(conversation.latestMessage?.messageTime).display:'暂无日期' }}</div>
          <!--              v-if="conversation.unreadCount > 0"-->
          <!--              v-if="hasUnreadConversations"-->
          <el-badge
              v-if="conversation.unreadCount>0"
              :value="conversation.unreadCount"
              :max="99"
              :class="{'unread-badge': conversation.unreadCount > 0}"

          />
        </div>
      </div>

      <!-- 搜索结果 -->
      <div v-if="searchResults.length > 0 && showSearchResults" class="search-results-section">
        <div class="section-title">搜索结果</div>
        <div
            v-for="contact in searchResults"
            :key="contact.id"
            class="search-result-card"
            @click.stop="startNewConversation(contact)"
        >
          <el-avatar :size="48" :src="contact.doctorAvatar || defaultAvatar2" class="search-avatar" />
          <div class="search-content">
            <div class="search-name">{{ contact.name }}</div>
            <div class="search-info">{{ contact.contactPhone || '无电话' }} - {{ contact.role.roleName || '无角色' }}</div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!showSearchResults && !hasConversations" description="暂无私信消息" />
    </div>

    <!-- 右侧：对话框 -->
    <div class="private-right-panel" v-if="currentConversation">
      <div class="chat-header">
        <el-avatar
            v-if="!isLoading"
            :size="40"
            :src="currentConversation.starterId===currentUser.id ? currentConversation.participant?.avatar : currentConversation.starter?.avatar"
        />
        <div v-if="!isLoading" class="chat-title">{{ currentConversation.starterId===currentUser.id ? currentConversation.participant?.name : currentConversation.starter?.name }}</div>
        <div class="chat-actions">
          <el-button type="danger" @click="deleteConversation">删除对话</el-button>
          <el-button type="primary" @click="closeConversation">关闭对话</el-button>
          <el-button type="warning" @click="closeChat">退出聊天</el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-messages" ref="messageContainer">
        <div
            v-for="msg in currentConversation.messages || []"
            :key="msg.id"
            class="chat-message"
            :class="{ 'is-sender': msg.senderId === currentUser.id, 'is-receiver': msg.senderId !== currentUser.id }"
        >
          <!-- 对方消息（左侧） -->
          <div v-if="msg.senderId!==currentUser.id" class="message-wrapper receiver-message">
            <el-avatar
                :size="36"
                :src="msg.sender?.avatar"
                class="message-avatar"
            />
            <div class="message-content">
              <div class="message-name">{{ msg.sender?.name }}</div>
              <div class="message-text message-bubble receiver-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatDateTime(msg.messageTime).display }}</div>
            </div>
          </div>
          <!-- 自己的消息（右侧） -->
          <div v-if="msg.senderId===currentUser.id"  class="message-wrapper sender-message">
            <el-avatar
                :size="36"
                :src="currentUser.doctorAvatar || defaultAvatar2"
                class="message-avatar"
            />
            <div class="message-content">
              <div class="message-name">{{ currentUser.username }}</div>
              <div class="message-text message-bubble sender-bubble">
                {{ msg.content }}
              </div>
              <div class="message-time">{{ formatDateTime(msg.messageTime).display }}</div>
            </div>
          </div>

        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input-container">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            placeholder="输入消息..."
            @keyup.enter="sendMessageByWS"
            class="chat-input"
        />
        <div class="chat-actions">
          <el-button type="primary" @click="sendMessageByWS">发送</el-button>
        </div>
      </div>

    </div>

    <!-- 无对话选中状态 -->
    <el-empty v-else class="no-conversation" description="请选择一个联系人开始对话" />
  </div>
</template>

<script setup>
import {ref, computed, onMounted, watch, nextTick, onUnmounted, toRefs, watchEffect} from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();

import { Search } from '@element-plus/icons-vue';
import axios from "axios";
import { formatDateTime } from "/src/utils/dateUtil.js";
import {ElMessage, ElMessageBox} from 'element-plus';
import { userStore } from '../store/index.js';
const userItemStore = userStore();
const  currentUser  = userItemStore.user;

import { messageStore } from '../store/message.js';
const messageItemStore = messageStore();
import request from "@/utils/request.js";

import {useWebSocket} from "@/composables/useWebSocket.js";
// 引入WebSocket功能
const { isConnected,subscribe,unsubscribe,messageCallbacks,sendMessage,wsReadyState,ws,connect } = useWebSocket();


// 注册消息回调
// 注册消息回调
let unsubscribeCallback; // 声明全局变量存储取消订阅函数

// 安全的计算属性：检查allConversations是否存在
const hasConversations = computed(() => {
  return messageItemStore.allConversations?.length > 0 || false;
});

// 安全的计算属性：检查unreadConversations是否存在
const hasUnreadConversations = computed(() => {
  return messageItemStore.unreadConversations?.length > 0 || false;
});



// 本地状态
const searchKeyword = ref('');
const searchResults = ref([]);
const showSearchResults = ref(false);
const currentConversation = ref({
});

const inputMessage = ref('');
const messageContainer = ref(null);




// 计算属性：未读/已读对话
// 优化后的未读/已读对话计算



// 修改 loadConversationMessages 方法
// 在script setup中添加加载状态
const isLoading = ref(true);

// 在加载对话数据的地方更新加载状态



const loadConversationMessages = async (conversationId) => {
  if (!conversationId) return
  isLoading.value = true
  try {
    const response = await request.get(`/message/getMessagesByConversationId/${conversationId}`)
    messageItemStore.setConversationMessages(conversationId, response.data || [])
    subscribeToConversation(conversationId)
  } catch (error) {
    ElMessage.error('加载消息失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 添加订阅对话函数
const subscribeToConversation = (conversationId) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(JSON.stringify({ action: "subscribe", conversationId }));
    console.log(`已订阅对话 ${conversationId} 的新消息`);
  }
};



// 处理新消息
const handleNewMessage = (event) => {

  try {
    const message = JSON.parse(event.data);
    if (message.type === "newMessage") {
      // 触发所有消息回调
      messageCallbacks.value.forEach(callback => callback(message));

      // 确保消息添加到store
      if (message.payload && message.payload.conversationId) {
        messageItemStore.addMessage(message.payload);

      }

      // 如果是当前对话，滚动到最新消息并更新UI
      if (currentConversation.value?.id === message.payload.conversationId) {

        nextTick(() => {
          scrollToLatestMessage();
          // 强制更新组件
          forceUpdate();
        });
      }
    }
  } catch (error) {
    console.error("处理消息时出错:", error);
  }
};

// 添加强制更新函数
const forceUpdate = () => {
  currentConversation.value = {
    ...currentConversation.value
  };
};

const scrollToLatestMessage = () => {
  const container = messageContainer.value
  if (container && container.scrollHeight) {
    container.scrollTop = container.scrollHeight
  }
}


// 修改openConversation方法
const openConversation = async (conversation) => {
  if (!conversation || !conversation.id) return;

  // 取消之前的订阅
  if (currentConversation.value?.id) {
    unsubscribe(currentConversation.value.id);
  }

  // 确保WebSocket连接
  if (!isConnected.value) {
    await connect();
  }

  // 订阅新对话
  const subscribed = await subscribe(conversation.id);
  if (!subscribed) {
    ElMessage.error('订阅对话失败');
    return;
  }

  // 加载消息
  await loadConversationMessages(conversation.id);

  // 更新当前对话
  currentConversation.value = conversation;
  messageItemStore.mCurrentConversation = conversation;
  // 标记为已读
  if (conversation.unreadCount > 0) {
    await messageItemStore.markAsRead(conversation.id,userItemStore.user.id);
  }

  // 滚动到底部
  nextTick(() => scrollToLatestMessage());
};

// const openConversation = async (conversation) => {
//   if (!conversation || !conversation.id) return;
//
//   // 使用深拷贝避免响应式问题
//   currentConversation.value = conversation;
//   // currentConversation.value = JSON.parse(JSON.stringify(conversation));
//
//   try {
//     // 确保WebSocket连接
//     if (!isConnected.value) {
//       await connect();
//     }
//
//     // 订阅对话
//     const subscribed = await subscribe(conversation.id);
//     if (!subscribed) {
//       throw new Error('订阅失败');
//     }
//
//     // 加载消息
//     await loadConversationMessages(conversation.id);
//
//
//     await markAsRead(conversation.id);
//
//
//     // 滚动到底部
//     nextTick(() => {
//       scrollToLatestMessage();
//     });
//   } catch (error) {
//     console.error('打开对话失败:', error);
//     ElMessage.error('打开对话失败，请重试');
//   }
// };

// const openConversation = async (conversation) => {
//   if (!conversation || !conversation.id) return;
//
//   // 取消之前的订阅
//   if (currentConversation.value?.id) {
//     unsubscribe(currentConversation.value.id);
//   }
//
//   currentConversation.value = conversation;
//
//   // 确保订阅成功
//   const maxRetries = 3;
//   let retryCount = 0;
//   let subscribed = false;
//
//   while (retryCount < maxRetries && !subscribed) {
//     subscribed = subscribe(conversation.id);
//     if (!subscribed) {
//       retryCount++;
//       await new Promise(resolve => setTimeout(resolve, 500));
//       console.log(`尝试重新订阅对话 ${conversation.id} (${retryCount}/${maxRetries})`);
//     }
//   }
//
//   if (!subscribed) {
//     ElMessage.error('订阅对话失败，请检查网络连接');
//     return;
//   }
//
//   // 处理未读消息等逻辑
//   if (currentConversation.value?.unreadCount > 0) {
//     await markAsRead(conversation.id);
//   }
//
//   await loadConversationMessages(conversation.id);
//   await nextTick(() => scrollToLatestMessage());
// };

// 修改sendMessageByWS方法
const sendMessageByWS = async () => {
  if (!currentConversation.value || inputMessage.value.trim() === '') return

  const wsMessage = {
    action: "message",
    senderId: currentUser.id,
    content: inputMessage.value,
    conversationId: currentConversation.value.id,
    type: 1
  }

  const isReady = isConnected.value && wsReadyState.value === WebSocket.OPEN
  if (!isReady) {
    console.warn('发送失败: 连接未就绪')
    connect()
    ElMessage.warning('WebSocket连接未就绪，正在尝试重新连接...')
    return
  }

  const success = sendMessage(wsMessage)
  if (success) {
    const localMessage = {
      id: Date.now(),
      senderId: currentUser.id,
      sender:{
        id:currentUser.id,
        name: currentUser.username,
        avatar: currentUser.doctorAvatar
      },
      content: inputMessage.value,
      conversationId: currentConversation.value.id,
      messageTime: new Date()
    }

    // 更新本地消息列表
    // 更新本地消息列表
    const index = messageItemStore.allConversations.findIndex(
        con => con.id === currentConversation.value.id
    );

    if (index !== -1) {
      if (!messageItemStore.allConversations[index].messages) {
        messageItemStore.allConversations[index].messages = [];
      }
      messageItemStore.allConversations[index].messages.push(localMessage);
      messageItemStore.allConversations[index].latestMessage = localMessage;
    }

    inputMessage.value = '';
    nextTick(() => scrollToLatestMessage());
  } else {
    ElMessage.error('消息发送失败，请重试');
  }
}





// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim() === '') {
    searchResults.value = [];
    showSearchResults.value = false;
    return;
  }

  const formKeyword = {
    teamId: null,
    keyword: searchKeyword.value
  };

  request.post(`/doctor/getAllDoctors`, formKeyword)
      .then(resp => {
        searchResults.value = resp.data || [];
        showSearchResults.value = searchResults.value.length > 0;
      })
      .catch(error => {
        console.error('搜索失败:', error);
        ElMessage.error('搜索失败，请稍后再试');
      });
};


// 开始新对话
const conversationData=ref({
  participantId:null,
  starterId:null,
});

const startNewConversation = async (contact) => {
  // 检查是否已有对话
  const existingConversation = messageItemStore.allConversations?.find(
      c => c.participantId === contact.id || c.starterId === contact.id
  );

  if (existingConversation) {
    // 已有对话，直接打开
    currentConversation.value = existingConversation;
    await loadConversationMessages(existingConversation.id);
  } else {
    conversationData.value.participantId = contact.id;
    conversationData.value.starterId = currentUser.id;
    try {
      // 创建新对话API调用
      const response = await request.post(`/conversation/createConversation`, conversationData.value);

      const newConversation = response?.data;
      if (!newConversation) {
        throw new Error('创建对话返回数据异常');
      }

      // 补充必要字段（如果API未返回）
      newConversation.latestMessage = {
        content: '开始了新对话',
        messageTime: new Date()
      };
      newConversation.participant =contact;
      newConversation.starter =currentUser;


          // 或直接操作数组并触发响应式更新
      messageItemStore.allConversations?.push(newConversation); // 如果allConversations是ref
      // messageItemStore.allConversations.value?.push(newConversation); // 如果allConversations是ref

      // 更新当前对话
      currentConversation.value = newConversation;

      ElMessage.success('对话创建成功');

      // 强制视图更新并加载消息
      await nextTick(async () => {
        await loadConversationMessages(newConversation.id);
        scrollToLatestMessage();
      });
    } catch (error) {
      ElMessage.error('对话创建失败，请稍后再试');
    }
  }
  showSearchResults.value = false;
};

// 关闭对话
const closeConversation = () => {
  currentConversation.value = null;
};

// 退出聊天，返回上一页
const closeChat = () => {
  router.go(-1);
};



// 标记对话为已读
// 标记已读函数修改为返回Promise
// const markAsRead = async (conversationId) => {
//   return new Promise((resolve, reject) => {
//     try {
//       // 后端更新，调用API标记为已读
//       request.put(`/conversation/markAsRead/${conversationId}/${currentUser.id}`)
//           .then(() => {
//             // Pinia更新，创建新数组，替换特定元素
//             messageItemStore.allConversations = messageItemStore.allConversations?.map(conversation => {
//               if (conversation.id === conversationId) {
//                 return {
//                   ...conversation,
//                   isReadCon: 1,
//                   unreadCount: 0
//                 };
//               }
//               return conversation;
//             });
//             messageItemStore.updateUnreadConversations();
//             resolve();
//           })
//           .catch(error => {
//             ElMessage.error('标记消息为已读失败');
//             reject(error);
//           });
//     } catch (error) {
//       ElMessage.error('标记消息为已读失败');
//       reject(error);
//     }
//   });
// };


// 删除对话
const deleteConversation = async () => {
  // 检查当前是否有选中的对话
  if (!currentConversation.value) return;

  try {
    // 调用 ElMessageBox.confirm 显示确认对话框
    // 该方法返回 Promise，用户点击确认或取消时会 resolve 对应字符串
    const action = await ElMessageBox.confirm(
        `确定要删除此对话吗？删除后将无法恢复消息记录？`,
        'warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    // 如果用户点击取消，直接返回
    if (action !== 'confirm') {
      return;
    }

    // 调用后端API删除对话
    await request.delete(`/conversation/deleteConversation/${currentConversation.value.id}`);

    // 获取当前对话ID并查找其在对话列表中的索引
    const conversationId = currentConversation.value.id;
    const conversationIndex = messageItemStore.allConversations?.findIndex(
        convo => convo.id === conversationId
    );

    // 从本地状态中删除对话
    if (conversationIndex !== -1) {
      messageItemStore.allConversations?.splice(conversationIndex, 1);
      ElMessage.success('对话删除成功');
    }

    // 关闭当前对话，显示空状态
    closeConversation();

  } catch (error) {
    // 处理异常情况（如网络错误、用户通过ESC关闭对话框等）
    console.error('删除对话操作异常:', error);

    // 仅当非用户取消操作时显示错误提示
    if (error !== 'cancel') {
      ElMessage.error('删除对话失败，请稍后再试');
    }
  }
};


// 监听当前对话变化
watch(
    currentConversation.value,
    (newConversation, oldConversation) => {
      if (newConversation !== oldConversation && oldConversation) {
        // 离开对话时标记为已读（如果有未读消息）
        if (oldConversation.unreadCount > 0) {
          messageItemStore.markAsRead(oldConversation.id,userItemStore.user.id);
        }
      }
    },
    { deep: true }
);


// 监听对话列表变化
watch(
    messageItemStore.allConversations,
    (newConversations) => {
      nextTick(() => {
        // 安全检查：确保有对话且当前没有选中的对话
        if (newConversations?.length > 0 && !currentConversation.value) {
          openConversation(newConversations[0]);
        }
      });
    },
    { deep: true }
);

onUnmounted(() => {
  // 移除消息监听
  if (ws.value) {
    ws.value.removeEventListener('message', handleNewMessage);
  }
  // 主动关闭WebSocket连接
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.close(1000, '组件卸载');
  }
  // 调用取消订阅函数
  if (unsubscribeCallback && typeof unsubscribeCallback === 'function') {
    unsubscribeCallback();
  }
});


const setupMessageSubscription = () => {

  // 定义回调函数
  const callback = (message) => {
    if (message.type == 'newMessage' && message.payload) {


      // 找到对应的对话
      const conversationIndex = messageItemStore.allConversations.findIndex(
          convo => convo.id == message.payload.conversationId
      );

      if (conversationIndex !== -1) {
        // 确保消息包含完整的发送者信息
        // 确保消息数据结构完整
        message.payload.sender = {
          id: message.payload.sender?.id || message.payload.senderId || 0,
          name: message.payload.sender?.name || '未知用户',
          avatar: message.payload.sender?.avatar || ''
        };

        // 更新对话最新消息
        messageItemStore.allConversations[conversationIndex].latestMessage = message.payload;
        // 如果是当前打开的对话，则标记为已读
        if (currentConversation.value?.id ==message.payload.conversationId) {
          messageItemStore.allConversations[conversationIndex].isReadCon = 1;
          messageItemStore.allConversations[conversationIndex].unreadCount = 0;
        } else {
          // 不是当前对话，增加未读计数
          messageItemStore.allConversations[conversationIndex].unreadCount =
              (messageItemStore.allConversations[conversationIndex].unreadCount || 0) + 1;
          messageItemStore.allConversations[conversationIndex].isReadCon = 0;
        }

        // 更新消息列表
        if (!messageItemStore.allConversations[conversationIndex].messages) {
          messageItemStore.allConversations[conversationIndex].messages = [];
        }
        messageItemStore.allConversations[conversationIndex].messages.push(message.payload);

        // 如果是当前对话，滚动到底部
        if (currentConversation.value?.id == message.payload.conversationId) {
          nextTick(() => scrollToLatestMessage());
        }

        // 更新未读对话列表
        messageItemStore.updateUnreadConversations();
      }
    }
  };

  // 将回调添加到消息回调数组
  messageCallbacks.value.push(callback);


  // 返回取消订阅函数
  unsubscribeCallback = () => {
    const index = messageCallbacks.value.indexOf(callback);
    if (index !== -1) {
      messageCallbacks.value.splice(index, 1);
    }
  };
};


// 组件挂载时初始化
onMounted(() => {
  // 连接WebSocket
  if (!isConnected.value) {
    useWebSocket().connect();
  }

  setupMessageSubscription();

  // 安全检查：确保有对话再订阅
  if (messageItemStore.allConversations?.length > 0) {
    const firstConversationId = messageItemStore.allConversations[0].id;
    subscribeToConversation(firstConversationId);
  }

  // 监听对话列表变化，自动打开第一个对话
  watchEffect(() => {
    if (messageItemStore.allConversations?.length > 0 && !currentConversation.value) {
      openConversation(messageItemStore.allConversations[0]);
    }
  });

});






</script>

<style scoped>
/* 私信容器 */
.private-message-container {
  display: flex;
  height: 100vh;
  min-height: 600px;
}

/* 左侧面板 */
.private-left-panel {
  width: 30%;
  border-right: 1px solid #eee;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

/* 右侧面板 */
.private-right-panel {
  width: 70%;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #eee;
  background-color: #fff;
}

/* 搜索容器 */
.search-container {
  padding: 10px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.search-input {
  width: 100%;
}

.search-icon {
  cursor: pointer;
  color: #909399;
  transition: color 0.2s;
}

.search-icon:hover {
  color: #409eff;
}

/* 对话列表 */
.conversation-section {
  padding: 10px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.conversation-card {
  padding: 10px;
  display: flex;
  visibility: visible;
  align-items: center;
  cursor: pointer;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: background-color 0.2s;
  position: relative;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.conversation-card.unread {
  background-color: #e6ffed;
  border-left: 3px solid #52c41a;
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.1);
}

.conversation-card:hover {
  background-color: #f5f5f5;
}

.conversation-avatar {
  margin-right: 10px;
}

.conversation-content {
  flex: 1;
  min-width: 0;
}

.conversation-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-preview {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-time {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
  min-width: 80px;
  text-align: right;
}

.unread-badge {
  position: absolute;
  right: 10px;
  top: 10px;
}

/* 搜索结果 */
.search-results-section {
  padding: 10px;
  border-top: 1px solid #eee;
}

.search-result-card {
  padding: 10px;
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: background-color 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.search-result-card:hover {
  background-color: #f5f5f5;
}

.search-avatar {
  margin-right: 10px;
}

.search-content {
  flex: 1;
}

.search-name {
  font-weight: 500;
}

.search-info {
  color: #666;
  font-size: 12px;
}

/* 聊天头部 */
.chat-header {
  padding: 10px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9f9;
}

.chat-title {
  font-weight: 500;
  margin-left: 10px;
  flex: 1;
}

/* 消息列表 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f5f5;
}

.chat-message {
  display: flex;
  margin-bottom: 15px;
  width: 100%;
}

.message-wrapper {
  display: flex;
  align-items: flex-end;
  max-width: 80%;
}

/* 接收者消息 (左侧) */
.receiver-message {
  justify-content: flex-start;
  margin-right: auto;
}

/* 发送者消息 (右侧) */
.sender-message {
  justify-content: flex-end;
  margin-left: auto;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 90%;
}

.sender-message .message-content {
  align-items: flex-end;
}

.receiver-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 8px 12px;
  border-radius: 18px;
  margin-bottom: 3px;
  max-width: 100%;
  word-wrap: break-word;
}

.sender-bubble {
  background-color: #409EFF;
  color: white;
  border-radius: 18px 18px 0 18px;
}

.receiver-bubble {
  background-color: cornsilk;
  color: #333;
  border-radius: 18px 18px 18px 0;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 2px;
}

.message-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

/* 输入框 */
.chat-input-container {
  padding: 10px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.chat-input {
  width: 100%;
  margin-bottom: 10px;
}

.chat-actions {
  display: flex;
  justify-content: flex-end;
}

/* 空状态 */
.no-conversation {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>